package cn.jietuo.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2021/2/26
 * @description: java1.4引入的NIO
 */
public class NioServer {

    private static List<SocketChannel> clientSocketChannels = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        // 创建NIO serverSocketChannel ，与BIO serverSocket类似
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定端口号
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
//        serverSocketChannel.bind();
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务启动成功");
        while (true) {
            // 获取客户端连接
            SocketChannel clientSocket = serverSocketChannel.accept();
            if (clientSocket != null) {
                // 如果有客户端连接
                System.out.println("连接成功");
                // 设置socketchannel为非阻塞
                clientSocket.configureBlocking(false);
                // 保存客户端连接到list中
                clientSocketChannels.add(clientSocket);
            }
            // 遍历连接进行数据读取
            Iterator<SocketChannel> iterator = clientSocketChannels.iterator();
            while (iterator.hasNext()) {
                SocketChannel socketChannel = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int read = socketChannel.read(byteBuffer);
                if (read > 0) {
                    System.out.println("接收到客户端信息：" + new String(byteBuffer.array()) + "--");
                } else if (read == -1) {
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }
            }
        }
    }
}
